package grape.wx.rest.mp;

import grape.wx.service.mp.MpProperties;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yangwei
 * Created at 2020/7/20 19:57
 */
@AllArgsConstructor
@Configuration
public class MpConfiguration {

    @Autowired
    private MpProperties properties;

    @Autowired(required = false)
    private List<IMpHandlerConfigure> mpHandlerConfigures;

    @ConditionalOnMissingBean
    @Bean
    public WxMpService wxMpService() {
        final List<MpProperties.MpConfig> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("请配置公众号相关配置");
        }
        WxMpService service = new CustomWxMpServiceImpl();

        service.setMultiConfigStorages(configs
                .stream().map(a -> {
                    WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
                    configStorage.setAppId(a.getAppId());
                    configStorage.setSecret(a.getSecret());
                    configStorage.setToken(a.getToken());
                    configStorage.setAesKey(a.getAesKey());
                    return configStorage;
                }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
        return service;
    }

    @ConditionalOnMissingBean
    @Bean
    public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);
        if (mpHandlerConfigures != null) {
            for (IMpHandlerConfigure mpHandlerConfigure : mpHandlerConfigures) {
                mpHandlerConfigure.configure(newRouter);
            }
        }
        return newRouter;
    }

}
